package com.rustic.server.controller.api;

import cn.hutool.core.collection.CollUtil;
import cn.xy.base.server.bean.IPage;
import cn.xy.base.server.utils.PageUtil;
import com.rustic.server.po.Category;
import com.rustic.server.service.CategoryService;
import com.rustic.server.vo.list.CategoryWebListVO;
import com.rustic.server.vo.CategoryVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import cn.xy.commons.core.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 表[category]对应的前台接口
 *
 * @author auto
 *
 */

@Slf4j
@RestController
@RequestMapping("/api/category")
@Api(tags = {"分类接口"})
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @ApiOperation(value = "分类-列表")
    @GetMapping("/list")
    public Result<Page<CategoryWebListVO>> list(IPage page) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //FIXME 根据需要修改搜索条件
        Page<Category> pageData = categoryService.page(page.toPage(), queryWrapper);
        List<Category> categoryList = pageData.getRecords();
        if (CollUtil.isEmpty(categoryList)) {
            return Result.data(new Page<>());
        }
        List<CategoryWebListVO> results = categoryService.toWebListVo(categoryList);
        return Result.data(PageUtil.toPage(pageData, results));
    }

    @ApiOperation(value = "分类-详情")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "分类id"),
    })
    @GetMapping("/detail")
    public Result<CategoryVO> detail(int id) {
        if (id <= 0) {
            return Result.error(CategoryService.CATEGORY_NOT_EXIST);
        }
        Category category = categoryService.getById(id);
        if (category == null) {
            return Result.error(CategoryService.CATEGORY_NOT_EXIST);
        }
        CategoryVO categoryVO = new CategoryVO(category);
        return Result.data(categoryVO);
    }

}
